﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;

namespace FMSpaceShooter.Data
{
    public sealed class HighscoreFile
    {
        private const string fileName = "scores.xml";
        private static DataContractSerializer serializer = new DataContractSerializer(typeof(List<LocalScore>), new List<Type> { });
        public static List<LocalScore> GetHighscores()
        {
            if (File.Exists(fileName))
            {
                using (var file = new FileStream(fileName, FileMode.Open))
                {
                    return (List<LocalScore>)serializer.ReadObject(file);
                    
                }
            }
            else
            {
                return new List<LocalScore>();
            }
        }

        public static bool AddScore(LocalScore score)
        {
            List<LocalScore> scores = GetHighscores();

            scores.Add(score);
            try
            {
                using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    serializer.WriteObject(writer, scores);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
